import logging
from logging.handlers import RotatingFileHandler

from flask import Flask, render_template, g
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf
from redis import StrictRedis

from config import my_config
from info.utils.common import user_login_data

mysql_db = SQLAlchemy()
redis_db = None  # type: StrictRedis


def setup_log(run_level):
    # 设置日志的记录等级
    logging.basicConfig(level=my_config[run_level].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def get_app(run_level):
    setup_log(run_level)

    my_flask_app = Flask(__name__)
    my_flask_app.config.from_object(my_config[run_level])

    @my_flask_app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    @my_flask_app.errorhandler(404)
    @user_login_data
    def page_not_found(_):
        user = g.user
        data = {"user_info": user.to_dict() if user else None}
        return render_template('news/404.html', data=data)

    from info.utils.common import host_news_class
    my_flask_app.add_template_filter(host_news_class)

    global mysql_db
    mysql_db.init_app(my_flask_app)
    global redis_db
    redis_db = StrictRedis()
    Session(my_flask_app)
    CSRFProtect(my_flask_app)

    from .modules.index.index import index_blueprint
    my_flask_app.register_blueprint(index_blueprint)
    from .modules.passport.views import passport_blueprint
    my_flask_app.register_blueprint(passport_blueprint)
    from .modules.news.views import news_blueprint
    my_flask_app.register_blueprint(news_blueprint)
    from .modules.user.views import user_blueprint
    my_flask_app.register_blueprint(user_blueprint)
    from .modules.admin.views import admin_blueprint
    my_flask_app.register_blueprint(admin_blueprint)

    # print(my_flask_app.url_map)
    return my_flask_app
